export default {
    data() {
        return {
            originalWidth: 0,
            originalHeight: 0,
            shouArea: false,
            _onResize: null,
        };
    },
    methods: {
        resizeMap(rectList) {
            const img = this.$refs.image;
            if (!img) return;

            if (!Array.isArray(rectList)) {
                rectList = this.rectList;
            }

            if (!this.originalWidth || !this.originalHeight) {
                if (!img.naturalWidth || !img.naturalHeight) return;
                this.originalWidth = img.naturalWidth;
                this.originalHeight = img.naturalHeight;
            }

            const scaleX = img.clientWidth / this.originalWidth;
            const scaleY = img.clientHeight / this.originalHeight;

            this.rectList = rectList.map((item) => ({
                ...item,
                coords: this.scaleCoords(item.originCoords, scaleX, scaleY),
            }));

            this.shouArea = true;
        },
        scaleCoords(coords, scaleX, scaleY) {
            return coords
                .split(",")
                .map((value, index) =>
                    index % 2 === 0
                        ? Math.round(value * scaleX)
                        : Math.round(value * scaleY)
                )
                .join(",");
        },
    },
    mounted() {
        // 保存引用，避免解绑失败
        this._onResize = () => this.resizeMap(this.rectList);

        window.addEventListener("resize", this._onResize);

        if (typeof this.handleAreaClick === "function") {
            document.addEventListener("click", this.handleAreaClick);
        }
    },
    beforeDestroy() {
        if (this._onResize) {
            window.removeEventListener("resize", this._onResize);
        }

        // 只有当函数存在时才尝试解绑
        if (typeof this.handleAreaClick === "function") {
            document.removeEventListener("click", this.handleAreaClick);
        }
    }
};
